<template>
  <div class="order-container">
    <div class="text-[20px] font-[600] text-[#222] mb-[24px]">My Orders</div>
    <div>
      <div class="table_header">
        <div class="table_header_item" style="width: 70px"></div>
        <div class="table_header_item" style="width: 160px">Order Number</div>
        <div class="table_header_item" style="width: 120px">Type</div>
        <div class="table_header_item flex-[5]">Name</div>
        <div class="table_header_item" style="width: 80px">Quantity</div>
        <div class="table_header_item" style="width: 150px">Total Order Amount</div>
        <div class="table_header_item" style="width: 40px"></div>
      </div>
      <!-- 加载状态 -->
      <div
        v-if="loading"
        class="loading-container min-h-[300px] text-[#7A7A7A] text-[16px] font-medium flex justify-center items-center">
        <div class="loading-spinner"></div>
        <span>Loading orders...</span>
      </div>

      <!-- 空状态 -->
      <div v-else-if="orders.length === 0" class="text-center">
        <img src="@/assets/noData.webp" class="w-[64px] mx-auto" alt="no orders" />
        <div class="text-[#7A7A7A] text-[16px] font-medium">No orders found</div>
      </div>

      <!-- 列表内容 -->
      <div v-else class="table_content">
        <div
          v-for="(order, index) in orders"
          :key="order.order_id"
          class="table_content_item"
          :class="{ expanded: expandedOrders.includes(order.order_id as any) }">
          <div class="table_content_main">
            <div class="table_content_item_item" style="width: 70px">
              <img :src="order.product?.cover" :alt="order.product?.title" class="order-image" />
            </div>
            <div
              class="table_content_item_item text-[#7A7A7A] text-center"
              style="font-weight: 400; width: 160px">
              {{ order.order_id }}
            </div>
            <div class="table_content_item_item" style="width: 120px">
              <span class="order-type">
                {{ getProductTypeName(order.product?.product_type) }}
              </span>
            </div>
            <div class="table_content_item_item flex-[5]">{{ order.name }}</div>
            <div class="table_content_item_item" style="width: 80px">{{ order.quality }}</div>
            <div
              class="table_content_item_item"
              style="width: 150px; font-size: 16px; font-weight: 600">
              ${{ order.price }}
            </div>
            <div class="table_content_item_item" style="width: 40px">
              <button
                @click="toggleExpand(order.order_id)"
                class="expand-button"
                :class="{ expanded: expandedOrders.includes(order.order_id as any) }">
                <svg
                  width="16"
                  height="16"
                  viewBox="0 0 24 24"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg">
                  <path
                    d="M6 9L12 15L18 9"
                    stroke="currentColor"
                    stroke-width="2"
                    stroke-linecap="round"
                    stroke-linejoin="round" />
                </svg>
              </button>
            </div>
          </div>

          <div v-if="expandedOrders.includes(order.order_id as any)" class="table_content_details">
            <div class="gap-[10px]">
              <div class="flex align-center gap-[8px]">
                <div class="font-[600] text-[#222]">Payment Method</div>
                <div class="font-[400] text-[#7A7A7A]">
                  {{ order.pay_method == '1' ? 'Shopify Payments' : '-' }}
                </div>
              </div>
              <!-- <div class="flex align-center gap-[8px]">
                <div class="font-[600] text-[#222]">Payment Status</div>
                <div class="font-[400] text-[#7A7A7A]">
                  {{ getPaymentStatusName(order.status) }}
                </div>
              </div> -->

              <div class="flex align-center gap-[8px]">
                <div class="font-[600] text-[#222]">Order Status</div>
                <div class="font-[400] text-[#7A7A7A]">
                  {{ getPaymentStatusName(order.status) }}
                </div>
              </div>
              <div class="flex align-center gap-[8px]">
                <div class="font-[600] text-[#222]">Payment Time</div>
                <div class="font-[400] text-[#7A7A7A]">
                  {{ order.pay_time || '-' }}
                </div>
              </div>
              <div class="flex align-center gap-[8px]">
                <div class="font-[600] text-[#222]">Shipping Address</div>
                <div class="font-[400] text-[#7A7A7A]">
                  {{ order.shipping_address || '-' }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载更多 -->
        <div v-if="pagination.isLoadingMore" class="load-more-container">
          <div class="loading-spinner"></div>
          <span>Loading more orders...</span>
        </div>
        <div
          v-else-if="!pagination.hasMore && orders?.length > pagination.size"
          class="text-center py-8">
          <NoMore />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, onUnmounted } from 'vue';
  import { UserAPI } from '@/api/user';
  import { ElMessage } from 'element-plus';
  import type { Order } from '@/types/order';
  import { getProductTypeName, getPaymentStatusName } from '@/types/order';
  import NoMore from '@/components/NoMore.vue';

  defineOptions({
    name: 'Order',
  });

  // 响应式数据
  const orders = ref<Order[]>([]);
  const loading = ref(false);
  const expandedOrders = ref<number[]>([]);
  const pagination = ref({
    start: 0,
    size: 10,
    total: 0,
    hasMore: true,
    isLoadingMore: false,
  });

  // 切换展开/关闭
  const toggleExpand = (orderId: any) => {
    const index = expandedOrders.value.indexOf(orderId);
    if (index > -1) {
      expandedOrders.value.splice(index, 1);
    } else {
      expandedOrders.value.push(orderId);
    }
  };

  // 获取订单列表
  const fetchOrders = async (isLoadMore = false) => {
    try {
      if (isLoadMore) {
        pagination.value.isLoadingMore = true;
      } else {
        loading.value = true;
        pagination.value.start = 0;
        orders.value = [];
      }

      const params = {
        start: pagination.value.start,
        size: pagination.value.size,
      };

      const response = await UserAPI.getOrders(params);

      if (response.data) {
        // 假设 response.data 是订单数组，或者包含订单数组和分页信息的对象
        const responseData = response.data;
        console.log(responseData, 'responseData');

        const newOrders = responseData.order_list;

        if (isLoadMore) {
          orders.value = [...orders.value, ...newOrders];
        } else {
          orders.value = newOrders;
        }

        // 更新分页信息
        if (!Array.isArray(responseData)) {
          // 如果响应数据包含分页信息
          pagination.value.total = responseData.total || pagination.value.total + newOrders.length;
          pagination.value.hasMore =
            responseData.has_more !== undefined
              ? responseData.has_more
              : newOrders.length === pagination.value.size;
          pagination.value.start =
            responseData.next_start !== undefined
              ? responseData.next_start
              : pagination.value.start + newOrders.length;
        } else {
          // 如果响应数据直接是数组，根据数组长度判断是否有更多数据
          pagination.value.hasMore = newOrders.length === pagination.value.size;
          pagination.value.start += newOrders.length;
        }

        console.log('订单列表加载成功:', response);
      }
    } catch (error) {
      console.error('获取订单列表失败:', error);
      ElMessage.error('Failed to obtain the order list...');
    } finally {
      loading.value = false;
      pagination.value.isLoadingMore = false;
    }
  };

  // 加载更多
  const loadMore = () => {
    if (pagination.value.hasMore && !loading.value && !pagination.value.isLoadingMore) {
      fetchOrders(true);
    }
  };

  // 监听滚动事件
  const handleScroll = () => {
    if (loading.value || !pagination.value.hasMore || pagination.value.isLoadingMore) return;
    const el = document.documentElement;
    if (el.scrollTop + window.innerHeight >= el.offsetHeight - 60) {
      loadMore();
    }
  };

  // 页面加载时获取订单列表
  onMounted(() => {
    fetchOrders();
    window.addEventListener('scroll', handleScroll, { passive: true });
  });

  // 组件卸载时移除监听器
  onUnmounted(() => {
    window.removeEventListener('scroll', handleScroll);
  });
</script>

<style scoped lang="scss">
  .order-container {
    width: 100%;
    min-height: 100vh;
    padding: 24px;
    background: #fff;
  }

  .table_header {
    display: flex;
    align-items: center;
    border-radius: 8px;
    background: #f5f5f5;
    padding: 16px 32px;
    margin-bottom: 16px;
    gap: 10px;

    .table_header_item {
      color: #222;
      text-align: center;
      font-size: 15px;
      font-style: normal;
      font-weight: 600;
      line-height: normal;
    }
  }

  .table_content {
    gap: 10px;

    .load-more-container {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 20px 0;
      gap: 10px;

      .loading-spinner {
        border: 4px solid rgba(255, 255, 255, 0.3);
        border-top: 4px solid #f76b1b;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        animation: spin 1s linear infinite;
      }

      @keyframes spin {
        0% {
          transform: rotate(0deg);
        }
        100% {
          transform: rotate(360deg);
        }
      }
    }

    .table_content_item {
      border: 1px solid #e1e2e3;
      border-radius: 8px;
      margin-bottom: 12px;
      background: #fff;
      transition: all 0.3s ease;
      overflow: hidden;

      .table_content_main {
        display: flex;
        align-items: center;
        padding: 16px 32px;
        min-height: 80px;
        gap: 10px;

        .table_content_item_item {
          text-align: center;
          font-size: 14px;
          font-style: normal;
          font-weight: 500;
          line-height: normal;
          display: flex;
          align-items: center;
          justify-content: center;

          .order-image {
            width: 64px;
            height: 64px;
            object-fit: cover;
            border-radius: 8px;
          }

          .order-type {
            padding: 4px 12px;
            border-radius: 16px;
            font-weight: 500;
            color: #222;
          }

          .expand-button {
            background: none;
            border: none;
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            color: #666;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;

            &:hover {
              background: #f5f5f5;
              color: #222;
            }

            &.expanded {
              transform: rotate(180deg);
            }

            svg {
              transition: transform 0.3s ease;
            }
          }
        }
      }

      .table_content_details {
        border-top: 1px solid #f5f5f5;
        padding: 16px;

        .details-content {
          display: grid;
          grid-template-columns: 1fr 1fr 1fr;
          gap: 32px;

          .details-section {
            h4 {
              color: #222;
              font-size: 16px;
              font-weight: 600;
              margin-bottom: 16px;
              padding-bottom: 8px;
              border-bottom: 2px solid #f76b1b;
            }

            .detail-row {
              display: flex;
              margin-bottom: 12px;
              font-size: 14px;

              span:first-child {
                color: #666;
                min-width: 80px;
                margin-right: 8px;
              }

              span:last-child {
                color: #222;
                font-weight: 500;
              }

              .status {
                padding: 2px 8px;
                border-radius: 12px;
                font-size: 12px;
                font-weight: 500;

                &.已发货 {
                  background: #e8f5e8;
                  color: #388e3c;
                }

                &.待发货 {
                  background: #fff3e0;
                  color: #f57c00;
                }

                &.已完成 {
                  background: #e3f2fd;
                  color: #1976d2;
                }
              }
            }

            .action-buttons {
              display: flex;
              flex-direction: column;
              gap: 8px;

              .action-btn {
                padding: 8px 16px;
                border-radius: 6px;
                border: none;
                cursor: pointer;
                font-size: 14px;
                font-weight: 500;
                transition: all 0.3s ease;

                &.primary {
                  background: #f76b1b;
                  color: white;

                  &:hover {
                    background: #e55a0f;
                  }
                }

                &.secondary {
                  background: #f5f5f5;
                  color: #666;
                  border: 1px solid #e1e2e3;

                  &:hover {
                    background: #e8e8e8;
                    color: #222;
                  }
                }

                &.danger {
                  background: #ffebee;
                  color: #d32f2f;
                  border: 1px solid #ffcdd2;

                  &:hover {
                    background: #ffcdd2;
                    color: #b71c1c;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  // 响应式设计
  @media (max-width: 768px) {
    .table_header {
      padding: 12px 16px;

      .table_header_item {
        font-size: 12px;
      }
    }

    .table_content_item {
      .table_content_main {
        padding: 12px 16px;
        flex-wrap: wrap;
        gap: 8px;

        .table_content_item_item {
          font-size: 12px;
          min-width: 80px;
        }
      }

      .table_content_details {
        padding: 16px;

        .details-content {
          grid-template-columns: 1fr;
          gap: 16px;
        }
      }
    }
  }
</style>
